package top.bug.blog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.bug.blog.common.BasePO;
import top.bug.blog.constant.CommonConstants;
import top.bug.blog.entity.dto.common.BatchRequest;
import top.bug.blog.entity.po.SysNotice;
import top.bug.blog.entity.po.User;
import top.bug.blog.enums.ErrorCode;
import top.bug.blog.exception.BussinessException;
import top.bug.blog.mapper.SysNoticeMapper;
import top.bug.blog.mapper.UserMapper;
import top.bug.blog.service.SysNoticeService;
import top.bug.blog.utils.StrUtils;

import javax.annotation.Resource;
import java.util.List;

import static top.bug.blog.utils.StrUtils.isNotBlank;

/**
 * @author <a href="https://github.com/jiusi66">九思.</a>
 * @email 10837907@qq.com
 * @from <a href="https://www.52bug.top">递归茶馆-www.52bug.top</a>
 * @description 公告模块 实现类
 */
@Service
public class SysNoticeServiceImpl extends ServiceImpl<SysNoticeMapper, SysNotice> implements SysNoticeService {
    @Resource
    private SysNoticeMapper sysNoticeMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    public Page<SysNotice> getList(SysNotice queryRequest) {
        Page<SysNotice> page = new Page<>(1, 10);
        String title = queryRequest.getTitle();
        String status = queryRequest.getStatus();
        LambdaQueryWrapper<SysNotice> queryWrapper = new LambdaQueryWrapper<SysNotice>()
                .like(isNotBlank(title), SysNotice::getTitle, title)
                .eq(isNotBlank(status), SysNotice::getStatus, status);
        sysNoticeMapper.selectPage(page, queryWrapper);
        for (SysNotice record : page.getRecords()) {
            String createBy = record.getCreateBy();
            User user = userMapper.selectById(createBy);
            if (null == user) {
                continue;
            }
            record.setCreateUserName(user.getNickname());
        }
        return page;
    }

    @Override
    public Boolean add(SysNotice addRequest) {
        if (null == addRequest) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        // 必填项校验
        String title = addRequest.getTitle();
        String content = addRequest.getContent();
        String status = addRequest.getStatus();
        if (StrUtils.isAnyBlank(title, content)) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        SysNotice notice = new SysNotice();
        BeanUtil.copyProperties(addRequest, notice);
        // 默认值填充
        if (StrUtil.isBlank(status)) {
            notice.setStatus(CommonConstants.STATUS_ENABLE);
        }
        // 保存用户（唯一性由数据库层面进行控制）
        boolean save = false;
        try {
            save = this.save(notice);
        } catch (DuplicateKeyException e) {
            throw new BussinessException(ErrorCode.DATA_ALREADY_EXISTED);
        }
        return save;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(BatchRequest batchRequest) {
        if (null == batchRequest || CollUtil.isEmpty(batchRequest.getIds())) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        return this.removeBatchByIds(batchRequest.getIds());
    }

    @Override
    public List<SysNotice> getAllNotices() {
        // 获取所有状态正常的公告
        List<SysNotice> notices = sysNoticeMapper.selectList(new LambdaQueryWrapper<SysNotice>()
                .eq(SysNotice::getStatus, CommonConstants.STATUS_ENABLE)
                // 根据创建日期倒序
                .orderByDesc(BasePO::getCreateOn)
        );
        // 补充创建用户信息
        for (SysNotice notice : notices) {
            String createBy = notice.getCreateBy();
            if (StrUtil.isBlank(createBy)) {
                continue;
            }
            User user = userMapper.selectById(createBy);
            notice.setCreateUserName(user.getNickname());
        }
        return notices;
    }

    @Override
    public Boolean edit(SysNotice updateRequest) {
        if (null == updateRequest || StrUtil.isEmpty(updateRequest.getId())) {
            throw new BussinessException(ErrorCode.PARAM_NOT_COMPLETE);
        }
        SysNotice notice = new SysNotice();
        BeanUtil.copyProperties(updateRequest, notice);
        return this.updateById(notice);
    }

}